package com.caszx.chargingpile.fragment.user;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSONException;
import com.app.base.adapter.BaseClickRecyclerAdapter;
import com.app.base.adapter.BaseHeadFootAdapter;
import com.app.base.fragment.BaseNetViewFragment;
import com.app.jsonparse.JSONParse;
import com.app.utils.DiskUser;
import com.app.utils.DividerGridItemDecoration;
import com.caszx.chargingpile.R;
import com.caszx.chargingpile.activity.PayActivity;
import com.caszx.chargingpile.entity.EntityChargeOrder;
import com.caszx.chargingpile.entity.EntityStoreupOrders;
import com.caszx.chargingpile.eventbus.CommentBus;
import com.caszx.chargingpile.eventbus.EventBusAction;
import com.caszx.chargingpile.eventbus.OrderPayBus;
import com.caszx.chargingpile.holder.user.OrderChargeHolder;
import com.caszx.chargingpile.holder.user.OrderReservateHolder;
import com.caszx.chargingpile.http.ConstantUrl;
import com.caszx.chargingpile.utils.SnackbarHelp;
import com.rey.material.app.Dialog;
import com.rey.material.app.DialogFragment;
import com.rey.material.app.SimpleDialog;

import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.event.EventBus;
import http.okhttp.OkHttpUtils;
import http.okhttp.callback.JsonCallback;
import okhttp3.Call;

/**
 * 订单记录->充电订单
 */
public class UserOrderChargeFragment extends BaseNetViewFragment {


    private RecyclerView mRecyclerView;
    private BaseHeadFootAdapter<EntityChargeOrder> mRecyclerAdapter;
    private List<EntityChargeOrder> mItems;
    private DecimalFormat decimalFormat = new DecimalFormat("￥###.##");
    private double chargeFees;

    public static UserOrderChargeFragment newInstance(double chargeFees, String chargeOrders) {
        UserOrderChargeFragment fragment = new UserOrderChargeFragment();
        Bundle bundle = new Bundle();
        bundle.putDouble("chargeFees", chargeFees);
        bundle.putString("chargeOrders", chargeOrders);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        EventBus.getDefault().register(this);
        if (getArguments() != null) {
            chargeFees = getArguments().getDouble("chargeFees");
            String chargeOrders = getArguments().getString("chargeOrders");
            mItems = JSONParse.parseArray(chargeOrders, EntityChargeOrder.class);
        }
    }


    /**
     * 评价完后的回调
     */
    public void onEvent(CommentBus action) {

        if (mRecyclerAdapter != null && mItems != null) {
            for (int i = 0; i < mItems.size(); i++) {
                if (mItems.get(i).ordersId.equals(action.orderId)) {
                    mItems.get(i).commentstatus = "1";
                    mRecyclerAdapter.notifyItemChanged(i);
                    return;
                }
            }
        }
    }

    private int mPayPosition = -1;

    public void onEvent(OrderPayBus action) {
        this.mPayPosition = action.position;
        getChargePrice(action.orederId);
    }


    public void onEvent(String action) {
        if (EventBusAction.ACTION_USER_PAY_SUCCESS.equals(action)) {
            if (mPayPosition != -1) {
                mItems.get(mPayPosition).paystatus = "1";
                mRecyclerAdapter.notifyItemChanged(mPayPosition);
                mPayPosition = -1;
            }
        }
    }

    @Override
    protected void onLoad() {
        showContentView();
    }

    @Override
    protected View initOnloadedView() {
        View view = getActivity().getLayoutInflater().inflate(
                R.layout.fragment_user_order_record, null);
        TextView txt_total_fee = (TextView) view.findViewById(R.id.txt_total_fee);
        txt_total_fee.setText("充电消费总额 " + decimalFormat.format(chargeFees));
        initRecyclerView(view);
        return view;
    }

    private void initRecyclerView(View view) {

        mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        mRecyclerView.setBackgroundResource(R.color.white);
        mRecyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setHasFixedSize(true);
        DividerGridItemDecoration itemDecoration = new DividerGridItemDecoration(getActivity());
        mRecyclerView.addItemDecoration(itemDecoration);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerAdapter = new BaseHeadFootAdapter<>(R.layout.item_user_order_charge, OrderChargeHolder.class);
        mRecyclerView.setAdapter(mRecyclerAdapter);
        mRecyclerAdapter.setDatas(mItems);
        mRecyclerAdapter.setOnItemClickListener(new BaseClickRecyclerAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                getordersDetail(mRecyclerAdapter.getItems().get(position).ordersId);
            }
        });
    }


    private void getordersDetail(String ordersId) {
        showProgressDialog("获取订单详情");
        OkHttpUtils.post()
                .url(ConstantUrl.URL_ORDERS_DETAIL_)
                .addParams("ordersId", ordersId)
                .tag(this)
                .build()
                .execute(new JsonCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        dissmissProgressDialog();
                        // showErrorView(R.string.error_network);
                        SnackbarHelp.showSnackbarMsg(getActivity(), getString(R.string.error_network));
                    }

                    @Override
                    public void onResponse(JSONObject response) {
                        dissmissProgressDialog();
                        JSONObject resultJsonObject = response.optJSONObject("result");
                        if (resultJsonObject != null) {
                            int code = resultJsonObject.optInt("code");
                            if (code < 0) {
                                //error
                                // DialogHelp.showDialogOnlyMesg(resultJsonObject.optString("msg"),null);
                                //showErrorView(resultJsonObject.optString("msg"));
                                SnackbarHelp.showSnackbarMsg(getActivity(), resultJsonObject.optString("msg"));
                            } else {
                                try {

                                    StringBuilder builder = new StringBuilder();
                                    builder.append("桩号:").append(response.optString("pileNo")).append("\n");
                                    builder.append("枪号:").append(response.optString("gunNo")).append("\n");
//                                  builder.append("电站名称:").append(response.optString("stationName")).append("\n");
//                                  builder.append("订单号:").append(response.optString("ordersId")).append("\n");
                                    builder.append("开始时间:").append(response.optString("sTime")).append("\n");
                                    builder.append("结束时间:").append(response.optString("eTime")).append("\n");
                                    builder.append("用电量:").append(response.optString("chargePower")).append("\n");
                                    builder.append("充电费用:").append(response.optString("chargeFees")).append("\n");
                                    builder.append("总费用:").append(response.optString("totalFees")).append("\n");
                                    builder.append("时长（秒）:").append(response.optString("timeLong")).append("\n");

                                    SimpleDialog.Builder builderDialog = new SimpleDialog.Builder(R.style.SimpleDialogLight);
                                    builderDialog.title("订单详情");
                                    builderDialog.message(builder.toString());
                                    builderDialog.positiveAction("确定");
                                    DialogFragment fragment = DialogFragment.newInstance(builderDialog);
                                    fragment.show(getChildFragmentManager(), null);
                                } catch (JSONException e) {
                                    SnackbarHelp.showSnackbarMsg(getActivity(), getString(R.string.error_parser_json));
                                    //showErrorView(R.string.error_parser_json);
                                }
                            }
                        }
                    }
                });
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    /**
     * 得到充电的费用
     */
    private void getChargePrice(String id) {
        showProgressDialog("获取未支付订单");
        HashMap<String, String> params = new HashMap<>();
        params.put("token", DiskUser.getStringValueByKey(getContext(), "token"));
        params.put("ordersId", id);
        OkHttpUtils.post()
                .url(ConstantUrl.URL_ORDERS_DETAIL)
                .params(params)
                .tag(this)
                .build()
                .execute(new JsonCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        dissmissProgressDialog();
                        // showErrorView(R.string.error_network);
                        SnackbarHelp.showSnackbarMsg(getActivity(), getString(R.string.error_network));
                    }

                    @Override
                    public void onResponse(JSONObject response) {
                        dissmissProgressDialog();
                        JSONObject resultJsonObject = response.optJSONObject("result");
                        if (resultJsonObject != null) {
                            int code = resultJsonObject.optInt("code");
                            if (code < 0) {
                                //error
                                // DialogHelp.showDialogOnlyMesg(resultJsonObject.optString("msg"),null);
                                //showErrorView(resultJsonObject.optString("msg"));
                                SnackbarHelp.showSnackbarMsg(getActivity(), resultJsonObject.optString("msg"));
                            } else {
                                try {
                                    Intent intent = new Intent(getActivity(), PayActivity.class);
                                    //充电的订单号
                                    intent.putExtra("ordersId", response.optString("ordersId"));
                                    //电站名称
                                    intent.putExtra("stationName", response.optString("stationName"));
                                    //时长
                                    intent.putExtra("timeLong", response.optLong("timeLong"));
                                    //时间段
                                    intent.putExtra("timeSlot", response.optString("timeSlot"));
                                    //用电量
                                    intent.putExtra("changePower", response.optDouble("changePower"));
                                    //充电费用
                                    intent.putExtra("chargeFees", response.optDouble("chargeFees"));
                                    //服务费
                                    intent.putExtra("serverFees", response.optDouble("serverFees"));
                                    //停车费
                                    intent.putExtra("stopFees", response.optDouble("stopFees"));
                                    //总费用
                                    intent.putExtra("totalFees", response.optDouble("totalFees"));
                                    startActivity(intent);
                                } catch (JSONException e) {
                                    SnackbarHelp.showSnackbarMsg(getActivity(), getString(R.string.error_parser_json));
                                    //showErrorView(R.string.error_parser_json);
                                }
                            }
                        }
                    }
                });
    }
}
